package com.jiang.jixiang.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;

import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.UserInfoBean;
import com.jiang.jixiang.databinding.ActivityRetrieveBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.countdown.CountDown;
import com.ws.universal.tools.countdown.TimeCount;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 找回密码
 */
public class RetrievePwdActivity extends BaseActivity implements NetWorkListener {
    private ActivityRetrieveBinding binding;
    private Intent intent;

    private TimeCount timeCount;

    private String phoneParams;
    private String areaParams;
    private String codeParams;

    private String pwdParams;
    private String passwordParams;

    private UserInfoBean userInfoBean;
    private int btnSignIn = 1;//当前按钮阶段
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;


    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity("RegistActivity", this);
        binding = ActivityRetrieveBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        intent = getIntent();
        areaParams = intent.getStringExtra("areaParams");
        binding.tvArea.setText(areaParams);
    }

    @Override
    protected void initView() {
        binding.inTitle.titleTextTv.setVisibility(View.GONE);
        binding.btnSubmit.setChangeAlphaWhenPress(true);
        binding.inTitle.titleLeftBtn.setOnClickListener(view -> {
            finish();
        });


        timeCount = new TimeCount();
        timeCount.setCountDown(new CountDown() {
            @Override
            public void onTick(long millisUntilFinished) {
                binding.btnGetCode.setEnabled(false);
                //binding.tvGetCode.setText(StringUtils.getString("重新发送", "(", millisUntilFinished / 1000 + ")"));
                binding.btnGetCode.setText(StringUtils.getString(millisUntilFinished / 1000));
            }

            @Override
            public void onTickFinish() {
                binding.btnGetCode.setText(R.string.get_code);
                binding.btnGetCode.setEnabled(true);
                binding.btnGetCode.setTextColor(ContextCompat.getColor(getContext(), R.color.text_minor_color));
            }
        });


        binding.btnGetCode.setOnClickListener(view -> {
            if (checkParams(1)) {
                hideSoftInput(binding.btnGetCode);
                showProgressDialog(false);
                getCode();

            }

        });

        binding.btnSubmit.setOnClickListener(view -> {

            if (btnSignIn == 1) {
                if (checkParams(2)) {
                    hideSoftInput(binding.btnSubmit);
                    binding.edAccount.setInputType(TEXT_PASSWORD);
                    binding.edCode.setInputType(TEXT_PASSWORD);
                    binding.llCountry.setVisibility(View.GONE);
                    binding.llSend.setVisibility(View.GONE);
                    binding.edAccount.getText().clear();
                    binding.edCode.getText().clear();
                    binding.edCode.clearFocus();
                    binding.edAccount.requestFocus();
                    binding.edAccount.setHint(getString(R.string.password));
                    binding.edCode.setHint(getString(R.string.repeat_password));
                    binding.btnSubmit.setText(getString(R.string.submit));
                }
            } else {
                if (checkParams(3)) {
                    hideSoftInput(binding.btnSubmit);
                    retrievePassword();
                }

            }

        });


        binding.llCountry.setOnClickListener(view -> {

            Intent intent = new Intent(this, CountryActivity.class);
            intentActivityResultLauncher.launch(intent);

        });

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                    String tel = result.getData().getStringExtra(CountryActivity.resultCountyCode);
                    LogcatUtils.e("获取的 Tel " + tel);
                    binding.tvArea.setText(tel);
                }
            }

        });


    }


    @Override
    protected void FinishDesTroy() {
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }


    private boolean checkParams(int type) {
        phoneParams = binding.edAccount.getText().toString().trim();
        areaParams = binding.tvArea.getText().toString().trim();
        codeParams = binding.edCode.getText().toString().trim();
        if (type == 1) {
            if (TextUtils.isEmpty(phoneParams)) {
                ToastUtils.showShort(getString(R.string.phone_cannot_be_empty));
                return false;
            }
        } else if (type == 2) {
            if (TextUtils.isEmpty(phoneParams)) {
                ToastUtils.showShort(getString(R.string.phone_cannot_be_empty));
                return false;
            }
            if (TextUtils.isEmpty(codeParams)) {
                ToastUtils.showShort(getString(R.string.verification_code_cannot_be_empty));
                return false;
            }
        } else {
            pwdParams = binding.edAccount.getText().toString().trim();
            passwordParams = binding.edCode.getText().toString().trim();
            if (TextUtils.isEmpty(pwdParams)) {
                ToastUtils.showShort(getString(R.string.password_cannot_be_empty));
                return false;
            }
            if (!pwdParams.equals(passwordParams)) {
                ToastUtils.showShort(getString(R.string.two_passwords_are_inconsistent));
                return false;
            }
        }

        return true;
    }


    private void getCode() {
        Map<String, String> params = new HashMap<>();
        params.put("type", "repassword");
        params.put("area", areaParams);
        params.put("phone", phoneParams);
        okHttpModel.post(ApiUrl.smsCode_Api, params, ApiUrl.smsCode_Api_ID, this);
    }


    //找回密码
    private void retrievePassword() {
        Map<String, String> params = new HashMap<>();
        params.put("type", "mobile");
        params.put("area", areaParams);
        params.put("code", codeParams);
        params.put("phone", phoneParams);
        params.put("password", passwordParams);
        params.put("repassword", passwordParams);
        okHttpModel.post(ApiUrl.forgetPassword_Api, params, ApiUrl.forgetPassword_Api_ID, this);
    }

    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.smsCode_Api_ID:
            case ApiUrl.emailCode_Api_ID:

                stopProgressDialog();
                int time = data.optInt("time");
                timeCount.setmMillisInFuture(time * 1000);
                timeCount.start();
                ToastUtils.showLong(commonality.getMessage(), 3000);

                break;


            case ApiUrl.register_Api_ID://注册

                userInfoBean = GsonUtils.parseJObject(data.toString(), UserInfoBean.class);
                if (userInfoBean != null) {
                    PubDiaUtils.getInstance().saveUserInfo(data.toString());
                }
                CacheUtils.setString(Constants.token, data.optString("token"));
                CacheUtils.setString(Constants.client, "android");
                CacheUtils.setBoolean(Constants.isLogin, true);
                ManageActivity.removeActivity("LoginActivity");
                pageJump(RegistInviteActivity.class);
                finish();


                break;
            case ApiUrl.forgetPassword_Api_ID://找回密码
                ToastUtils.showShort(commonality.getMessage());
                loginAccount();
                break;
            case ApiUrl.login_Api_ID:
                CacheUtils.setString(Constants.token, data.optString("token"));
                CacheUtils.setString(Constants.client, "android");
                CacheUtils.setBoolean(Constants.isLogin, true);

                userInfoBean = GsonUtils.parseJObject(data.toString(), UserInfoBean.class);
                if (userInfoBean != null) {
                    PubDiaUtils.getInstance().saveUserInfo(data.toString());
                }

                ToastUtils.showShort(commonality.getMessage());
               /* if (userInfoBean.getFirst_login() == 1) {
                    pageJump(RegistInviteActivity.class);
                } else {
                    pageJump(MainActivity.class);
                }*/
                pageJump(MainActivity.class);
                BaseBusData baseBusData = new BaseBusData(BusCode.LogIn);
                EventBusUtil.postEvent(baseBusData);
                finish();
                ToastUtils.showShort(commonality.getMessage());
                break;

        }

    }

    private void loginAccount() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("code", codeParams);
        params.put("area", areaParams);
        params.put("password", passwordParams);
        params.put("type", "mobile");
        params.put("push_id", Constants.push_id);
        okHttpModel.post(ApiUrl.login_Api, params, ApiUrl.login_Api_ID, this);
    }


    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }
}
